//
//  StringExtension.swift
//  MGExtensionsKit
//
//  Created by Max on 2019/7/29.
//

import Foundation

extension String {
    /// 图片url获取图片宽高
    public static func imageSize(from urlString: String?) -> CGSize {
        if let URLString = urlString, URLString.count > 0 {
            let url = URL(string: URLString)
            let path = url?.lastPathComponent
            let components = path?.components(separatedBy: "_")
            if let sizeComponent = components, sizeComponent.count > 1 {
                let sizeString = sizeComponent.last?.lowercased()
                let whArray = sizeString?.components(separatedBy: "x")
                if let array = whArray, array.count == 2 {
                    let width = (array.first! as NSString).floatValue
                    let height = (array.last! as NSString).floatValue
                    if width > 0, height > 0 {
                        return CGSize(width: CGFloat(width), height: CGFloat(height))
                    }
                }
            }
        }
        return CGSize.zero
    }
    
    /// 图片url获取图片宽高比
    public static func widthHeightRatio(by urlString: String?, defaultSize: CGSize) -> CGFloat {
        let sizeFromUrl = String.imageSize(from: urlString)
        if sizeFromUrl.width > 0, sizeFromUrl.height > 0 {
            return sizeFromUrl.width/sizeFromUrl.height
        }
        return defaultSize.width > 0 && defaultSize.height > 0 ? defaultSize.width/defaultSize.height : 1.0
    }
    
    /// 价格转换
    public static func priceString(from price: Int) -> String {
        var priceString = "\(price/100)"
        var cent = price % 100
        if cent > 0 {
            if cent < 10 {
                priceString += ".0\(cent)"
            }else {
                if cent % 10 == 0 {
                    cent = cent/10
                }
                priceString += ".\(cent)"
            }
        }
        return priceString
    }
    
    /// 计算文本size
    public func size(font: UIFont, maxWidth: CGFloat) -> CGSize {
        let label = UILabel()
        label.font = font
        label.numberOfLines = 0
        label.text = self
        let size = label.sizeThatFits(CGSize(width: maxWidth, height: CGFloat(MAXFLOAT)))
        return size
    }
}

/// 时间格式化
extension String {
    /// 活动时间
    public var activityTimeString: String {
        let startDate = Date(dateString: self, format: "yyyy-MM-dd HH:mm:ss")
        var dayString = ""
        
        // 当前时间+48小时即为后天
        let threeDayTime = Date().timeIntervalSince1970+2*24*3600
        let threeDayDate = Date(timeIntervalSince1970: threeDayTime)
        if startDate.isInSameDay(to: threeDayDate) {
            dayString = "后天"
        }else if startDate.isTomorrow() {
            dayString = "明天"
        }else if startDate.isInSameDay(to: Date()) {
            dayString = "今天"
        }else {
            dayString = startDate.dateString(format: "M月d日 ")
        }
        
        var timeString = ""
        let startComponents = startDate.calendarComponents()
        if let minute = startComponents.minute, minute > 0 {
            timeString = startDate.dateString(format: "HH:mm")
        }else {
            timeString = "\(startComponents.hour ?? 0)点"
        }
        return "\(dayString)\(timeString)"
    }
    
    /// 活动时间少于10分
    public var timeIsLessThan10m: Bool {
        let startDate = Date(dateString: self, format: "yyyy-MM-dd HH:mm:ss")
        let difTime = startDate.timeIntervalSince1970 - Date().timeIntervalSince1970
        return (difTime > 0 && difTime <= 10*60)
    }
    
    public var javaDateToSocailDateString: String {
        var useDate = self
        if useDate.count > 19 {
            useDate = String(self[..<useDate.index(useDate.startIndex, offsetBy: 19)])
        }
        return Date(dateString: self, format: "yyyy-MM-dd HH:mm:ss").messageTimeString()
    }
    
    public static func nowDateToSocailDateString() -> String {
        return NSDate().description.javaDateToSocailDateString
    }
    
    public var timeComponents: (day: Int, hour: Int, minute: Int, second: Int) {
        let timeStamp = Date(dateString: self, format: "yyyy-MM-dd HH:mm:ss").timeIntervalSince1970
        let remaindTime = timeStamp - Date().timeIntervalSince1970
        if remaindTime > 0 {
            return Int(remaindTime).timeComponents
        }
        return (0, 0, 0, 0)
    }
}

public enum ImageCloudProcessorType {
    /// 以最长边等比例缩放，不做裁剪
    case scaleClip(targetSize: CGSize)
    /// 将原图等比缩放为延伸出指定w与h的矩形框外的最小图片，之后将超出的部分进行居中裁剪
    case aspectRatioScale(longestSideLength: CGFloat)
}

extension Extensive where Base == String {
    
    public func hasImageSuffix() -> Bool {
        guard (base.hasSuffix(".jpeg") ||
               base.hasSuffix(".jpg") ||
               base.hasSuffix(".png") ||
               base.hasSuffix(".gif") ||
               base.hasSuffix(".webp") ||
               base.hasSuffix(".bmp") ||
               base.hasSuffix(".tiff")) else {
            return false
        }
        return true
    }
    
    public var decimalFormatted: String? {
        guard let value = Double(base) else {
            return nil
        }
        Constants.sharedNumberFormatter.numberStyle = .decimal
        return Constants.sharedNumberFormatter.string(from: NSNumber(value: value))
    }
    
    /// 删除字符串最后的所有\n
    public func removingSuffixNewlineCharacters() -> String {
        guard base.hasSuffix("\n") else {
            return base
        }
        var copy = base
        copy.removeLast()
        return copy.mg.removingSuffixNewlineCharacters()
    }
    
}

extension String {
    
    /// 版本数字比价
    public func compare(to other: String) -> ComparisonResult {
        var currents = self.components(separatedBy: ".")
        var others = other.components(separatedBy: ".")
        
        // 位数不同，少的补0
        let count = max(currents.count, others.count)
        if currents.count < count {
            let more = Array(repeating: "0", count: count-currents.count)
            currents.append(contentsOf: more)
        }
        if others.count < count {
            let more = Array(repeating: "0", count: count-others.count)
            others.append(contentsOf: more)
        }
        
        for idx in 0..<count {
            if let c = Int(currents.value(at: idx) ?? "0"),
                let o = Int(others.value(at: idx) ?? "0") {
                if c > o {
                    return .orderedAscending
                } else if c < o {
                    return .orderedDescending
                }
            }
        }
        return .orderedSame
    }
}

public extension String {
    func localization() -> String {
        return NSLocalizedString(self, comment: self)
    }
}
